package com.hk.Mgr.web.controller.kyc;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.Constant;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Activity;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.ActivityReq;
import com.hk.commons.vo.ActivityRes;
import com.hk.service.kyc.IActivity;
import com.hk.service.sys.ISysUser;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/activityCtrl")
public class ActivityCtrl extends BaseCtrl {

	@Autowired
	private IActivity activityService;

	@Autowired
	private ISysUser sysUserService;

	private Logger logger = LoggerFactory.getLogger(ActivityCtrl.class);


	@Value("${file.imgUploadPath}")
	private String imgUploadPath;

	@Value("${file.tempUploadPath}")
	private String tempUploadPath;



	@Autowired
	public YingmiApiUtils utils;

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> updateActivity(@RequestBody ActivityReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Integer id = req.getId();
		
		logger.info("mgr/ActivityCtrl/update  id = " + id);
		Activity act = activityService.findById(id);
		
		try {
			if (act == null){
				resp.setMsg("参数不对：id is null！");
				resp.setResult(true);
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				return resp;
			} else {
				ReqToModelHelper.copyReqValueToModel(req, act);
				activityService.update(act);
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}
		} catch (Exception e) {
			logger.error("保存活动失败");
			resp.setMsg("保存活动失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
	
	/**
	 * 更改状态
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> updateStatus(@RequestBody ActivityReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		if(req == null || req.getId() == null || req.getStatus() == null){
			resp.setMsg("参数错误！");
			resp.setResult(false);
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Integer id = req.getId();
		Integer status = req.getStatus();
		String location = req.getLocation();
		
		logger.info("mgr/ActivityCtrl/updateStatus  id = {}, status={}, location={} ", id,   status, location);
		
		Activity act = activityService.findById(id);
		Boolean pushMsgStatus = false;

		String channel = act.getChannel();

		//如果活动发布状态从未发布改为已发表, 并且渠道为理财师版
		if(status == 1 && act.getStatus() == 0 && StringHelper.isNotEmpty(channel) && (channel.indexOf("2") >= 0 ||channel.indexOf("1") >= 0)){
			pushMsgStatus = true;
		}

		try {
			act.setStatus(status);

			act.setLocation(req.getLocation());

			activityService.update(act);
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());

			if(pushMsgStatus){
				logger.info("mgr/ActivityCtrl/updateStatus will start to send push msg");

				if(channel.indexOf("2") >= 0){
					logger.info("mgr/ActivityCtrl/updateStatus will start to send push msg to licaishi");
					activityService.pushActMsg(id, 2);
				}

				if(channel.indexOf("1") >= 0){
					logger.info("mgr/ActivityCtrl/updateStatus will start to send push msg to huacaitong");
					activityService.pushActMsg(id, 1);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("更新活动失败");
			resp.setMsg("更新活动失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 获得所有活动
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<ActivityRes>> listOrder(
			@RequestBody ActivityReq req) {
		ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();
		List<ActivityRes> orderReslist = new ArrayList<>();

		HqlFilter hqlFilter = new HqlFilter();

		if (StringUtils.isNotEmpty(req.getName())) {
			hqlFilter.addLKFilter("name", req.getName());
		}

		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");

		List<Activity> list = activityService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());

		for (Activity ag : list) {
			ActivityRes activityRes = activityService.getRes(ag);

			// 增添创建者姓名
			activityRes.setCreatorName(sysUserService.getNameById( ag.getCreator()));

			orderReslist.add(activityRes);
			resp.setResult(orderReslist);
			resp.setSize(orderReslist.size());
			resp.setResult(orderReslist);
		}

		return resp;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> save(@RequestBody ActivityReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Activity ag = new Activity();

		try {
			ReqToModelHelper.copyReqValueToModel(req, ag);

			ag.setStartTime(req.getStartTime());
			ag.setEndTime(req.getEndTime());
			//默认状态为未激活
			ag.setStatus(Constant.ACTIVITY_NO_ACTIVE);
			activityService.add(ag);
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());

		} catch (Exception e) {
			logger.error("保存活动失败");
			resp.setMsg("保存活动失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@ResponseBody
	public void doPost(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		File uploadPath  = new File(imgUploadPath);

		//获取根目录对应的真实物理路径
		logger.info("uploadPath == " + uploadPath);

		//如果目录不存在
		if (!uploadPath.exists()) {
			//创建目录
			uploadPath.mkdir();
		}

		//临时目录
		//File tempFile = new File(item.getName())构造临时对象
		File tempPath  = new File(tempUploadPath);

		logger.info("tempUploadPath == " + uploadPath);
		if (!tempPath.exists()) {
			tempPath.mkdir();
		}


		//从item_upload.jsp中拿取数据，因为上传页的编码格式跟一般的不同，使用的是enctype="multipart/form-data"
		//form提交采用multipart/form-data,无法采用req.getParameter()取得数据
		//String itemNo = req.getParameter("pic");
		//System.out.println("itemNo======" + itemNo);


		/********************************使用 FileUpload 组件解析表单********************/

		//DiskFileItemFactory：创建 FileItem 对象的工厂，在这个工厂类中可以配置内存缓冲区大小和存放临时文件的目录。
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		factory.setRepository(tempPath);



		//ServletFileUpload：负责处理上传的文件数据，并将每部分的数据封装成一到 FileItem 对象中。
		//在接收上传文件数据时，会将内容保存到内存缓存区中，如果文件内容超过了 DiskFileItemFactory 指定的缓冲区的大小，
		//那么文件将被保存到磁盘上，存储为 DiskFileItemFactory 指定目录中的临时文件。
		//等文件数据都接收完毕后，ServletUpload再从文件中将数据写入到上传文件目录下的文件中


		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(1000000 * 20);


		/*******************************解析表单传递过来的数据，返回List集合数据-类型:FileItem***********/

		try {

			List fileItems = upload.parseRequest(req);

			String itemNo = "";
			//Iterator iter = fileItems.iterator()取其迭代器
			//iter.hasNext()检查序列中是否还有元素
			for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
				//获得序列中的下一个元素
				FileItem item = (FileItem) iter.next();


				//判断是文件还是文本信息
				//是普通的表单输入域
				if(item.isFormField()) {
					if ("itemNo".equals(item.getFieldName())) {
						itemNo = item.getString();
					}
				}
				//是否为input="type"输入域
				if (!item.isFormField()) {
					//上传文件的名称和完整路径
					String fileName = item.getName();

					long size = item.getSize();
					//判断是否选择了文件
					if ((fileName == null || fileName.equals("")) && size == 0) {
						continue;
					}
					//截取字符串 如：C:\WINDOWS\Debug\PASSWD.LOG
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());

					// 保存文件在服务器的物理磁盘中：第一个参数是：完整路径（不包括文件名）第二个参数是：文件名称
					//item.write(file);
					//修改文件名和物料名一致，且强行修改了文件扩展名为gif
					//item.write(new File(uploadPath, itemNo + ".gif"));
					//将文件保存到目录下，不修改文件名
					item.write(new File(uploadPath, fileName));

					//将图片文件名写入打数据库
					//itemManager.uploadItemImage(itemNo, fileName);
					logger.info("fileName = " + fileName);
				}
			}
			//response.sendRedirect(req.getContextPath() + "/servlet/item/SearchItemServlet");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
